//
//  ZNNewSTableViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/9/7.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import MJRefresh

class ZNNewSTableViewController: BaseTableViewController {

    var isMe = false
    var titleString = ""
    var dataArray = [NewsModel]()
    var page = 1
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
        
        self.title = titleString
        self.tableView.separatorStyle = .none
        if self.isMe {
            PKhud.show()
            self.getMyArticle()
        }else{
            PKhud.show()
            self.getArticleList()
        }
        
        if !self.isMe {
            self.tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: { [weak self] in
                self?.page = 1
                self?.getArticleList()
            })
            self.tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: { [weak self] in
                self?.page = (self?.page)! + 1
                self?.getArticleList()
            })
            self.setRightBarButton(title: "我的收藏", imageName: "", action: #selector(rightBarButtonMethod), titleColor: "#000000")
        }
        
    }
    
    @objc func rightBarButtonMethod(){
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "ZNNewSTableViewController") as! ZNNewSTableViewController
        ctrl.isMe = true
        ctrl.titleString = "我的收藏"
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    func getMyArticle(){
        HttpRequest.requestData(.post, URLString: Api.articleMy.rawValue, parameters: nil) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                if let array = [NewsModel].deserialize(from: result["data"] as? [Any]) as? [NewsModel] {
                    self.dataArray = array
                    self.tableView.reloadData()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    func getArticleList(){
        HttpRequest.requestData(.post, URLString: Api.articleList.rawValue, parameters: ["pageNum":page,"pageSize":10]) { (result) in
            PKhud.hiden()
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            if result["msg"] as! String == "success"{
                if let array = [NewsModel].deserialize(from: result["data"] as? [Any]) as? [NewsModel] {
                    if self.page == 1 {
                        self.dataArray = array
                    }else{
                        self.dataArray += array
                    }
                    if array.count < 10 {
                        self.tableView.mj_footer.endRefreshingWithNoMoreData()
                    }
                    self.tableView.reloadData()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.dataArray.count
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = self.dataArray[indexPath.row]
        if model.img == "" {
            return 90
        }else{
            return UIScreen.ScreenWidth/(351/230)
        }
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = self.dataArray[indexPath.row]
        if model.img == "" {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ZXNewSNormalTableViewCell") as! ZXNewSNormalTableViewCell
            cell.reload(withModel: self.dataArray[indexPath.row])
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "ZXNewsImageTableViewCell") as! ZXNewsImageTableViewCell
            cell.reload(withModel: self.dataArray[indexPath.row])
            return cell
        }
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.dataArray[indexPath.row]
        let ctrl = NewsDetailViewController()
        ctrl.model = model
        var url = model.url
        if Utils.isLogined() {
            let id = Utils.getUserDefaulsFor(key: "id") as! String
            url = url + "?userId=\(id)"
        }
        ctrl.url = url
        ctrl.titleString = "咨询详情"
        self.navigationController?.pushViewController(ctrl, animated: true)
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
